package cn.ilikes.tools.nosql.jpa.metadatas.processor.validators;

import java.lang.reflect.Field;

import javax.persistence.Entity;
import javax.persistence.Table;

import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;
import cn.ilikes.tools.nosql.jpa.annotations.Index;
import cn.ilikes.tools.nosql.jpa.annotations.IndexColumn;
import cn.ilikes.tools.nosql.jpa.metadatas.EntityMetaData;

public class EntityIndexValidator implements EntityValidator {

	private Logger logger = Loggerfactory.instance(EntityIndexValidator.class);

	@Override
	public boolean entityValidator(Class<?> clazz, EntityMetaData entityMetaData) throws EntityValidatorException {
		if (Loggerfactory.isdebug(logger))
			logger.debug("start validator entity   proper set   @Index   and  @IndexColumn ");
		if (clazz.isAnnotationPresent(Index.class)) {
			if (!clazz.isAnnotationPresent(Entity.class) || !clazz.isAnnotationPresent(Table.class))
				throw new EntityValidatorException("this  entity : " + clazz.getSimpleName()
						+ " find @Index ,but not find @Entity  or  @Table  !  pealse find  @Index to class ! ");

		}
		{
			Index index_ = clazz.getAnnotation(Index.class);

			//设置@IndexColumn but 没有设置  @Index
			for (Field f : clazz.getDeclaredFields()) {
				if (f.isAnnotationPresent(IndexColumn.class)) {
					if (index_ != null && index_.index().equals(Index.index.no))
						throw new EntityValidatorException("this  entity : " + clazz.getSimpleName()
								+ " find @IndexColumn ,but not find @Index pealse set  @Index to class ! ");
				}

			}

		}
		return true;
	}

}
